package com.yj.suncity.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.bean.OfferBean;
import com.yj.suncity.bean.OfferListBean;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.PullToRefreshView;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.DialogUtils.ReshActivity;
import com.yj.suncity.utis.PullToRefreshView.OnFooterRefreshListener;
import com.yj.suncity.utis.PullToRefreshView.OnHeaderRefreshListener;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 个人接悬赏列表
 * 
 * @author Administrator
 * 
 */
public class UserOfferListActivity extends Activity implements OnClickListener,
		OnItemLongClickListener, OnFooterRefreshListener,
		OnHeaderRefreshListener {

	private Context context;
	private String userId;
	private String titleName;

	private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
	private boolean mRefreshFlag = false;// 判断是否刷新
	private PullToRefreshView mPullToRefreshView = null;
	private int pageNum = 1;
	private ListView mList_user_offer;
	private OfferAdapter adapter;
	private List<OfferBean> detailInfos;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_offer_user);
		context = this;
		userId = getIntent().getStringExtra("userid");
		titleName = getIntent().getStringExtra("titlename");

		findView();
		initData(1);

	}

	private void findView() {
		findViewById(R.id.btnHeadBack).setOnClickListener(this);
		((TextView) findViewById(R.id.txt_title_name)).setText(titleName);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		TextView emptyView = (TextView) findViewById(R.id.txt_empty);
		mList_user_offer = (ListView) findViewById(R.id.list_see_adv);
		mList_user_offer.setEmptyView(emptyView);
		mList_user_offer.setOnItemLongClickListener(this);
	}

	private void initData(int index) {
		String path = URLCon.悬赏 + "?action=myacceptofferlist&"
				+ "pagesize=20&pageindex=" + index + "&userid=" + userId;
		Log.d("", path);

		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null,
				mPullToRefreshView, mRefreshFlag, null, true, "正在加载......",
				new AsyncTaskUtil.ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						OfferListBean listBean = new OfferListBean(jsonObject);
						pageNum = Integer.valueOf(listBean.getTotalpage());
						if (mRefreshHeadFlag) {
							adapter = null;
						}
						if (adapter == null) {
							detailInfos = listBean.getOfferData();
							adapter = new OfferAdapter(detailInfos);
							mList_user_offer.setAdapter(adapter);
						} else {
							detailInfos.addAll(listBean.getOfferData());
							adapter.notifyDataSetChanged();
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	class OfferAdapter extends BaseAdapter {
		private List<OfferBean> offerBeans;

		public OfferAdapter(List<OfferBean> offerBeans) {
			this.offerBeans = offerBeans;
		}

		@Override
		public int getCount() {
			return offerBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return offerBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_offer_user_item, null);
				holder.mImg_logo = (ImageView) convertView
						.findViewById(R.id.img_logo);
				holder.mImg_logo.setVisibility(View.GONE);
				holder.mTxt_content = (TextView) convertView
						.findViewById(R.id.txt_offer_content);
				holder.mTxt_offer_give_num = (TextView) convertView
						.findViewById(R.id.txt_give_num);
				holder.mTxt_offer_finish = (TextView) convertView
						.findViewById(R.id.txt_is_finish);
				holder.mTxt_offer_finish_time = (TextView) convertView
						.findViewById(R.id.txt_finish_time);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			OfferBean offerBean = offerBeans.get(position);
			holder.mTxt_content.setText(offerBean.getUTask_name());
			holder.mTxt_offer_finish_time.setText(Utils
					.DateFormatDate(offerBean.getUHold_datetime()));
			holder.mTxt_offer_give_num.setText(offerBean.getUSilver_num());
			if (offerBean.getUIs_finish().equals("1")) {
				holder.mTxt_offer_finish.setText("已结束");
			} else {
				holder.mTxt_offer_finish.setText("未结束");
			}

			return convertView;
		}
	}

	class ViewHolder {
		ImageView mImg_logo;
		TextView mTxt_content;
		TextView mTxt_offer_give_num;
		TextView mTxt_offer_finish;
		TextView mTxt_offer_finish_time;
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final OfferBean offerBean = (OfferBean) mList_user_offer.getAdapter()
				.getItem(position);
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.backDialog(context, "确定删除已接悬赏吗？", true, new ReshActivity() {
			@Override
			public void reshActivity() {
				deleteOffer(offerBean.getId());
			}
		});
		return false;
	}

	/**
	 * 个人删除已接悬赏
	 */
	private void deleteOffer(String offerId) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		String path = URLCon.悬赏;
		pairs.add(new BasicNameValuePair("action", "delholdrecord"));
		pairs.add(new BasicNameValuePair("userid", userId));
		pairs.add(new BasicNameValuePair("id", offerId));
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, pairs, null,
				false, null, true, "正在删除......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
							mRefreshFlag = false;// 判断是否刷新
							indexPage = 1;
							initData(indexPage);
						} else {
							ToastUtil.ShowToast(context,
									jsonObject.optString("msg"));
						}

					}
				});
		asyncTaskUtil.execute(path);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = false;
				mRefreshFlag = true;

				++indexPage;
				if (indexPage > pageNum) {
					ToastUtil.ShowToast(context, "没有更多数据！");
					mPullToRefreshView.onFooterRefreshComplete();
					return;
				} else {
					initData(indexPage);
				}

				// mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1);

	}

	int indexPage = 1;

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = true;
				mRefreshFlag = true;
				// if (async != null) {
				// Utils.cancelTaskInterrupt(async);
				// async = null;
				// }
				indexPage = 1;// 刷新头部时将页数初始化为1
				initData(indexPage);
				// mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;

		default:
			break;
		}

	}

}
